package com.hitqz.robot.biz.flow.component.patrol;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hitqz.robot.api.business.enums.EquipmentEnum;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolTicketsDto;
import com.hitqz.robot.api.common.entity.PatrolPose;
import com.hitqz.robot.api.common.entity.RobotEquipment;
import com.hitqz.robot.api.common.entity.TicketsTask;
import com.hitqz.robot.biz.service.PatrolPoseService;
import com.hitqz.robot.biz.service.RobotEquipmentService;
import com.hitqz.robot.camera.EquipmentFactory;
import com.hitqz.robot.camera.IEquipmentService;
import com.hitqz.robot.camera.configure.EquipmentCmdEnum;
import com.hitqz.robot.camera.dto.EquipmentParamsDto;
import com.hitqz.robot.camera.dto.QueryParamsDto;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;

/**
 * @author xupkun
 * @date 2024/11/3
 */
@Slf4j
@LiteflowComponent(value = "SetChipParamsOrigin", name = "[巡检]设置芯片额外参数回原")
@AllArgsConstructor
public class SetChipParamsOrigin extends NodeComponent {

    private final RobotEquipmentService robotEquipmentService;

    private final EquipmentFactory equipmentFactory;

    private final PatrolPoseService patrolPoseService;

    @Override
    public void process() throws Exception {
        FlowContextDto dto =  this.getRequestData();
        if (isNeedSkip(dto)){
            log.info("跳过当前步骤");
            return;
        }
        TicketsTask task = dto.getTicketsTask();
        FlowPatrolTicketsDto params = JSONObject.parseObject(task.getParseOrderParams(), FlowPatrolTicketsDto.class);
        if (params.getPoseGroupId()==null){
            log.warn("没有姿态组信息,不执行");
            return;
        }
        List<RobotEquipment> chips = robotEquipmentService.list(Wrappers.<RobotEquipment>lambdaQuery()
                .eq(RobotEquipment::getType, EquipmentEnum.CHIP.getType())
                .eq(RobotEquipment::getIsRecordParam, 1));
        for (RobotEquipment chip : CollUtil.emptyIfNull(chips)) {
            IEquipmentService service = equipmentFactory.getServiceByBrand(chip.getBrand());
            if (service==null){
                return;
            }
            PatrolPose pose = patrolPoseService.getOne(Wrappers.<PatrolPose>lambdaQuery().eq(PatrolPose::getEquipmentId, chip.getId()).eq(PatrolPose::getGroupId, params.getPoseGroupId()).last("limit 1"));
            if (pose==null){
                return;
            }
            List<EquipmentParamsDto> paramsDtos = JSONArray.parseArray(pose.getJson(), EquipmentParamsDto.class);
            QueryParamsDto queryParamsDto = new QueryParamsDto();
            queryParamsDto.setPassword(chip.getPassword());
            queryParamsDto.setUsername(chip.getUsername());
            queryParamsDto.setPort(chip.getPort());
            queryParamsDto.setChannel(chip.getChannel());
            queryParamsDto.setIp(chip.getIp());
            service.setEquipmentParams(queryParamsDto, service.getDeviceParamsData(queryParamsDto, EquipmentCmdEnum.GET_ORIGIN_PARAMS) , false);
        }

    }


    private boolean isNeedSkip(FlowContextDto dto){
        try {
            TicketsTask lastTicketsTask = dto.getLastTicketsTask();
            if (lastTicketsTask == null) {
                return false;
            }
            //当前参数
            TicketsTask task = dto.getTicketsTask();
            FlowPatrolTicketsDto params = JSONObject.parseObject(task.getParseOrderParams(), FlowPatrolTicketsDto.class);
            FlowPatrolPreAndEndTicketsDto endParams = JSONObject.parseObject(task.getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
            Integer currentTargetPosId = params.getPosId() != null ? params.getPosId() : (endParams.getEndPosId() != null ? endParams.getEndPosId() : null);
            //上一次的参数
            FlowPatrolTicketsDto lastParams = JSONObject.parseObject(lastTicketsTask.getParseOrderParams(), FlowPatrolTicketsDto.class);
            FlowPatrolPreAndEndTicketsDto lastEndParams = JSONObject.parseObject(lastTicketsTask.getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
            Integer lastTargetPosId = lastParams.getPosId() != null ? lastParams.getPosId() : (lastEndParams.getEndPosId() != null ? lastEndParams.getEndPosId() : null);
            if (!Objects.equals(currentTargetPosId,lastTargetPosId)){
                return false;
            }
            if (Objects.equals(params.getPoseGroupId(),lastParams.getPoseGroupId())){
                log.info("当前工单任务与上一次工单任务姿态组相同");
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

}
